package com.lhb.rabbit.service;

import com.lhb.rabbit.config.MqConstants;
import lombok.Data;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BasicPublisher {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public String publish(String name){
        return publish2mq1(name)+publish2mq2(name)+publish3Mq3(name)+publish4Mq4(name);
    }
    /**
     * 一般用法，推送消息，消息会进行持久化
     * @param ans
     * @return
     */
    private String publish2mq1(String ans) {
        String msg = "Durable msg =" + ans;
        System.out.println("publish: "+ msg);
        rabbitTemplate.convertAndSend(MqConstants.exchange,MqConstants.routing,msg);
        return msg;
    }

    /**
     * 推送一个非持久化的消息，mq重启时，这个消息会消失，持久化的数据则不会
     * @param ans
     * @return
     */
    public String publish2mq2(String ans) {

        MessageProperties properties = new MessageProperties();
        //设置消息属性为非持久化
        properties.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
        Message message = rabbitTemplate.getMessageConverter().toMessage("NonDurable = " + ans, properties);

        rabbitTemplate.convertAndSend(MqConstants.exchange,MqConstants.routing,message);
        System.out.println("publish"+message);
        return message.toString();
    }

    private String publish3Mq3(String name){
        String msg = "Define msg" + name;
        rabbitTemplate.convertAndSend(MqConstants.exchange, MqConstants.routing, msg, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setHeader("lhb","cc");
                //消息非持久化
                message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
                return message;
            }
        });
        return msg;
    }

    private String publish4Mq4(String name){
        NonSerDo serDo = new NonSerDo(12, "lhb");
        System.out.println("publish:"+serDo);
        rabbitTemplate.convertAndSend(MqConstants.exchange,MqConstants.routing,serDo);
        return serDo.toString();
    }

    @Data
    public static class NonSerDo{
        private Integer age;
        private String name;

        public NonSerDo(Integer age, String name) {
            this.age = age;
            this.name = name;
        }
    }
}
